<template>
    <div class="share-page">
        <!-- 页面头部 -->
        <div class="header">
            <h1>邀请好友一起变美</h1>
            <p>分享专属二维码，与闺蜜一起享受美丽时光</p>
        </div>



        <!-- 截图预览区域 -->
        <div v-if="screenshotUrl" class="preview-container mb30">
            <h3 class="preview-title">海报预览</h3>
            <div class="preview-box">
                <img :src="screenshotUrl" alt="截图预览" class="preview-image">
            </div>
            <div class="share-actions" style="margin-bottom: 10px;">
                <!-- 手动保存按钮 -->
                <button @click="saveScreenshot" class="share-btn copy-link">
                    保存到本地
                </button>
            </div>

            <!-- 可选：添加说明 -->
            <p class="preview-note">
                点击上方按钮、或长按图片保存
            </p>
        </div>



        <!-- 二维码展示区 -->
        <div v-if="!screenshotUrl" class="qr-code-container">
            <div class="qr-card-div" id="screenshot-area">
                <h2>美丽邀请函</h2>
                <div class="avatar-placeholder">
                    <img v-if="CustomerInfo && CustomerInfo.avatar" :src="CustomerInfo.avatar" alt="头像" />
                    <img v-else src="@/assets/images/mr/logo.png" alt="头像" />
                    <!-- 如果有用户头像可以启用上面的img标签 -->
                </div>
                <div class="qr-wrapper">
                    <!-- 这里应该是实际的二维码组件或图片 -->
                    <div class="qr-placeholder">
                        <QrCode :url="qrUrl" title="" :isDown="false" :isEdit="false" @edit="" />
                        <div class="scan-line">
                        </div>
                    </div>
                </div>
                <p class="invite-text">扫描二维码，开启美丽之旅</p>
                <div class="user-info">
                    <span>来自: </span>
                    <span v-if="CustomerInfo.nickName">{{ CustomerInfo.nickName }}</span>
                    <span v-else>您的好友</span>
                </div>
            </div>
        </div>

        <!-- 分享按钮区 -->
        <div class="share-actions">
            <button class="share-btn wechat" @click="shareToSession">
                <i class="el-icon-chat-line-round"></i>
                微信分享
            </button>
            <button class="share-btn moments" @click="shareToTimeline">
                <i class="el-icon-orange"></i>
                朋友圈
            </button>
            <!-- 生成按钮 -->
            <button class="share-btn copy-link" @click="generateScreenshot">
                <i class="el-icon-picture-outline-round"></i>
                {{ isGenerating ? '生成海报...' : '生成海报' }}
            </button>
        </div>

        <!-- 美丽宣言 -->
        <div class="beauty-quotes">
            <div class="quote-item">
                <p>"美丽是一种态度，分享是一种美德"</p>
            </div>
        </div>
        <div class="share-png-div" :class="{ 'fade-out': isShareFading }" v-show="isShare || isShareFading">
            <img src="@/assets/images/mr/share.png" alt="" class="share-png">
        </div>

    </div>
</template>

<script>
import QrCode from "../components/QrCode.vue";
import { getConfigKey } from '@/api/system/config' // 导入配置API
import { getWxSign } from '@/api/wechat'
import { set } from "nprogress";

import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';

export default {
    name: 'SharePage',
    components: { QrCode },
    data() {
        return {
            qrUrl: '',
            CustomerInfo: {},
            wxConfig: {},
            isShare: false,
            isShareFading: false,
            // 截图
            isGenerating: false,
            screenshotUrl: null
        };
    },
    mounted() {
        this.getQrCode();
        // 判断是否在微信浏览器中
        const isWechat = () => {
            return navigator.userAgent.toLowerCase().includes('micromessenger');
        };

        if (isWechat()) {
            this.init();            
        }
    },
    methods: {
        init() {
            getConfigKey('wx.appId').then(response => {
                this.appId = response.msg ? response.msg : ""

                if (!this.appId || this.appId == '') {
                    this.$message.error('未配置微信AppID，请在系统配置中设置wx.appId')
                    return
                }
                console.log("this.appId", this.appId)

                const url = window.location.href.split('#')[0];
                getWxSign({ url: url }).then(res => {
                    console.log("res", res.data);
                    this.wxConfig = res.data
                    this.initWechatShare()

                })
            });

        },
        copyLink() {
            // 复制链接逻辑
            this.$message.success('链接已复制到剪贴板');
        },
        getQrCode() {
            this.CustomerInfo = JSON.parse(localStorage.getItem('CustomerInfo'));
            console.log("CustomerInfo", this.CustomerInfo);
            if (this.CustomerInfo && this.CustomerInfo.deptId) {
                this.qrUrl = window.location.origin + '/app?deptId=' + this.CustomerInfo.deptId
            } else {
                this.qrUrl = window.location.origin + '/app?deptId=100'
            }
            console.log("qrUrl", this.qrUrl);
        },
        // 初始化微信分享
        initWechatShare() {

            // 这里需要调用后端接口获取微信签名等信息
            // 暂时使用示例数据
            this.shareData = {
                title: '邀请好友一起变美',
                desc: '分享专属二维码，与闺蜜一起享受美丽时光！',
                link: this.qrUrl,
                imgUrl: (this.CustomerInfo) ? this.CustomerInfo.avatar : '' // 替换为实际的logo地址
            };
            console.log("shareData", this.shareData);
            // 配置微信JS SDK
            if (typeof wx !== 'undefined') {
                console.log("wx-开始初始化");
                // 实际项目中需要通过后端接口获取签名信息
                wx.config({
                    debug: false,
                    appId: this.appId, // 必填，公众号的唯一标识
                    timestamp: this.wxConfig.timestamp, // 必填，生成签名的时间戳
                    nonceStr: this.wxConfig.nonceStr, // 必填，生成签名的随机串
                    signature: this.wxConfig.signature, // 必填，签名
                    jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
                });
                console.log("wx-初始化完成");
                wx.ready(() => {
                    // 分享给朋友
                    wx.updateAppMessageShareData({
                        title: this.shareData.title,
                        desc: this.shareData.desc,
                        link: this.shareData.link,
                        imgUrl: this.shareData.imgUrl,
                        success: (res) => {
                            console.log(res)
                            console.log('分享给朋友配置成功');
                        }
                    });

                    // 分享到朋友圈
                    wx.updateTimelineShareData({
                        title: this.shareData.title,
                        link: this.shareData.link,
                        imgUrl: this.shareData.imgUrl,
                        success: (res) => {
                            console.log(res)
                            console.log('分享到朋友圈配置成功');
                        }
                    });
                });

                wx.error(function (res) {
                    console.error('微信JS SDK配置失败', res);
                });
            } else {
                console.log("wx-未初始化");

            }
        },

        // 分享给朋友
        shareToSession() {
            this.isShare = true
            this.isShareFading = false
            setTimeout(() => {
                this.isShareFading = true
                setTimeout(() => {
                    this.isShare = false
                    this.isShareFading = false
                }, 500)
            }, 3000)
        },

        // 分享到朋友圈
        shareToTimeline() {
            this.isShare = true
            this.isShareFading = false
            setTimeout(() => {
                this.isShareFading = true
                setTimeout(() => {
                    this.isShare = false
                    this.isShareFading = false
                }, 500)
            }, 3000)
        },
        generateScreenshot() {
            // 防止重复点击
            if (this.isGenerating) return;

            this.isGenerating = true;
            this.screenshotUrl = null;

            // 获取要截图的区域（这里用 #screenshot-area，根据实际修改）
            const element = document.getElementById('screenshot-area');

            // 生成截图
            html2canvas(element, {
                useCORS: true,      // 解决跨域图片问题
                scale: 2,           // 提高清晰度
                logging: false      // 关闭控制台日志
            }).then(canvas => {
                // 转换为DataURL（预览用）
                this.screenshotUrl = canvas.toDataURL('image/png');
                this.isGenerating = false;
            }).catch(error => {
                console.error('截图失败:', error);
                this.isGenerating = false;
                alert('截图生成失败！请检查浏览器或网络设置。');
            });
        },

        saveScreenshot() {
            if (!this.screenshotUrl) return;

            // 使用 file-saver 保存（触发浏览器下载）
            saveAs(this.screenshotUrl, 'screenshot.png');

            // 可选：保存后清空预览（保持用户操作习惯）
            // this.screenshotUrl = null;
        }
    }
}
</script>

<style scoped lang="scss">
.share-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #fdf6f9 0%, #fff0f5 100%);
    padding: 20px;
    box-sizing: border-box;
}

.header {
    text-align: center;
    margin-bottom: 40px;
    padding-top: 20px;

    h1 {
        font-size: 28px;
        color: #ff6b9d;
        margin-bottom: 15px;
        font-weight: 600;
    }

    p {
        font-size: 16px;
        color: #888;
        line-height: 1.6;
    }
}

.qr-code-container {
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
}

.qr-card-div {
    background: url('../../assets/images/mr/share-bg.jpg') no-repeat center right;
    background-size: auto 100%;
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(255, 107, 157, 0.15);
    padding: 20px;
    text-align: center;
    min-width: 320px;
    height: 530px;
    width: 98%;
    max-width: 400px;
    position: relative;
    overflow: hidden;

    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 5px;
        background: linear-gradient(90deg, #ff6b9d, #ffb6c1, #ff6b9d);
    }

    .avatar-placeholder {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: linear-gradient(135deg, #ff9ec5, #ffb6c1);
        margin: 0 auto 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 3px solid white;
        box-shadow: 0 5px 15px rgba(255, 107, 157, 0.2);
        position: absolute;
        bottom: 300px;
        right: 20px;

        img {
            width: 100%;
            height: 100%;
            border-radius: 50%;

        }
    }

    h2 {
        color: #ff6b9d;
        font-size: 22px;
        margin-bottom: 25px;
        font-weight: 500;
        position: absolute;
        bottom: 200px;
        right: 20px;
    }

    .qr-wrapper {
        padding: 15px;
        background: #f8f8f8;
        border-radius: 15px;
        margin-bottom: 20px;
        display: inline-block;
    }

    .qr-placeholder {
        width: 150px;
        height: 150px;
        background: linear-gradient(135deg, #ffd1dc, #ffb6c1);
        border-radius: 5px;
        position: relative;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        bottom: 50px;
        right: 20px;

        &::before {
            content: "";
            position: absolute;
            width: 40px;
            height: 40px;
            background: white;
            border-radius: 5px;
        }

    }

    .invite-text {
        color: #ff6b9d;
        font-size: 15px;
        font-weight: 500;
        position: absolute;
        bottom: 10px;
        right: 15px;
    }

    .user-info {
        position: absolute;
        bottom: 10px;
        left: 10px;

        span {
            color: #888;
            font-size: 12px;
        }
    }
}

@keyframes scan {
    0% {
        top: 0;
    }

    100% {
        top: 100%;
    }
}

.share-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-bottom: 40px;
    flex-wrap: wrap;

    .share-btn {
        border: none;
        border-radius: 50px;
        padding: 12px 40px;
        font-size: 16px;
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);

        &.wechat {
            background: #07c160;
            color: white;

            &:hover {
                background: #06ad56;
                transform: translateY(-3px);
            }
        }

        &.moments {
            background: #ffcc00;
            color: white;

            &:hover {
                background: #e6b800;
                transform: translateY(-3px);
            }
        }

        &.copy-link {
            background: #ff6b9d;
            color: white;

            &:hover {
                background: #ff528a;
                transform: translateY(-3px);
            }
        }

        i {
            font-size: 20px;
        }
    }
}

.beauty-quotes {
    text-align: center;

    .quote-item {
        p {
            font-style: italic;
            color: #ff6b9d;
            font-size: 18px;
            position: relative;
            display: inline-block;
            padding: 0 30px;

            &::before,
            &::after {
                content: "";
                font-size: 40px;
                position: absolute;
                color: #ffb6c1;
            }

            &::before {
                left: -10px;
                top: -20px;
            }

            &::after {
                right: -10px;
                bottom: -30px;
            }
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .share-page {
        padding: 15px;
    }

    .header {
        h1 {
            font-size: 24px;
        }

        p {
            font-size: 14px;
        }
    }

    .share-actions {
        gap: 12px;

        .share-btn {
            padding: 10px 15px;
            font-size: 14px;

            i {
                font-size: 18px;
            }
        }
    }

    .beauty-quotes {
        .quote-item {
            p {
                font-size: 16px;
            }
        }
    }
}

.share-png-div {
    width: auto;
    height: 100vh;
    position: fixed;
    right: 0;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 10;
    background: #00000020;
    text-align: right;
    display: flex;
    justify-content: flex-end;
    opacity: 1;
    transition: opacity 0.5s ease;

    &.fade-out {
        opacity: 0;
    }
}

.share-png {
    width: auto;
    max-width: 500%;
    height: 100vh;
}



// 截图开始
.preview-container {
    margin-top: 2rem;
    background: white;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.preview-title {
    text-align: center;
    margin-top: 0;
    color: #2c3e50;
}

.preview-box {
    max-width: 100%;
    height: auto;
    margin: 1rem 0;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
}

.preview-image {
    width: 100%;
    height: auto;
    display: block;
}

.preview-note {
    color: #7f8c8d;
    font-size: 0.9rem;
    margin-top: 1rem;
}

// 截图结束</style>